package com.oocl.euc.core.attachment.controller;

import com.oocl.euc.core.attachment.model.Attachment;
import com.oocl.euc.core.attachment.repository.AttachmentRepository;
import com.oocl.euc.core.builder.AttachmentBuilder;
import com.oocl.euc.core.common.ITTestBase;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

public class AttachmentControllerIT extends ITTestBase {

    @Autowired
    AttachmentBuilder attachmentBuilder;

    @Autowired
    AttachmentRepository attachmentRepository;

    @After
    public void reset() {
        attachmentRepository.deleteAll();
    }

    @Test
    public void should_return_success_with_attachment_when_given_correct_multipart_file() throws Exception {
        Attachment attachment = attachmentBuilder.defaultBuilder()
                .withFileName("test.txt")
                .withContentType("multipart/form-data")
                .withContent("Hello World!".getBytes("UTF-8"))
                .create();
        mockMvc.perform(
                MockMvcRequestBuilders.fileUpload("/rest/attachment/upload")
                        .file(new MockMultipartFile("file", attachment.getFileName(), attachment.getContentType(), attachment.getContent())))
                .andExpect(status().isOk())
                .andDo(print())
                .andReturn().getResponse().getContentAsString();
    }

    @Test
    public void should_return_not_found_when_given_wrong_attachment_id() throws Exception {
        mockMvc.perform(get("/rest/attachment/download").param("fileId", "10000"))
                .andExpect(status().isNotFound());
    }

    @Test
    public void should_download_attachment_when_given_exist_attachment_id() throws Exception {
        String content = "Hello World!";
        Attachment attachment = attachmentBuilder.defaultBuilder()
            .withFileName("test.txt")
            .withContent(content.getBytes("UTF-8"))
            .saveToDB();

        mockMvc.perform(get("/rest/attachment/download").param("fileId", attachment.getId().toString()))
            .andExpect(jsonPath("$").value(content));
    }
}